﻿/* Write a program that finds the most frequent number in an array. Example:
	{4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3}  4 (5 times)
*/

using System;

class MostFrequent
{
    static void Main()
    {
        uint N;
        bool iProvided = false;
        do
        {
            if (iProvided == true) Console.WriteLine("Error! Please enter an integer.");
            else iProvided = true;
            Console.Write("Enter N: ");
        } while (UInt32.TryParse(Console.ReadLine(), out N) == false || N < 1);

        iProvided = false; //reset iProvided
        int[] nums = new int[N];
        for (int i = 0; i < nums.Length; i++)
        {
            iProvided = false;
            do
            {

                if (iProvided == true) Console.WriteLine("Error! Please enter an integer.");
                else iProvided = true;
                Console.Write("Enter element {0}: ", i + 1);
            } while (Int32.TryParse(Console.ReadLine(), out nums[i]) == false);
        }

        int mostf = 0, mostf_I = 0, tmp = 0; //most frequent - times of occurrance, most frequent index (stack)
        for (int i = 0; i < nums.Length-1; i++)
        {
            mostf = 0;
            for (int j = i+1; j < nums.Length; j++)
            {
                if (nums[j] == nums[i])
                {
                    mostf++;
                }
            }
            if (mostf > tmp)
            {
                tmp = mostf;
                mostf_I = nums[i];
            }

            if (tmp > nums.Length / 2)
            {
                break;
            }
           
        }
        Console.WriteLine("Most frequent: {0} (met {1} times)", mostf_I, tmp+1);



    }
}
